package com.spring.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.entity.PageBean;
import com.spring.entity.User;
import com.spring.service.UserService;
import com.spring.util.JwtToken;
import com.spring.util.MyUtil;
import com.spring.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();

    @Autowired
    private UserService userService;

    /**
     *网页登陆接口
     * @param identityID
     * @param password
     * @param httpSession
     * @return
     * @throws UnsupportedEncodingException
     * @throws JsonProcessingException
     */
    @PostMapping("/web/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam String identityID,
                                @RequestParam String password, HttpSession httpSession) throws UnsupportedEncodingException, JsonProcessingException {
        ResponseEntity responseEntity = ResponseEntity.ok();
        User userFromBase = userService.selectUserByIdentityId(identityID);
        if(userFromBase.getIdentityID().equals(identityID) &&
                userFromBase.getPassword().equals(password)) {
            //给用户jwt加密生成token
            String token = JwtToken.sign(userFromBase, 60L * 1000L * 30L);
            //封装成对象返回给客户端
            responseEntity.putDataValue("userId", userFromBase.getIdentityID());
            responseEntity.putDataValue("token", token);
            httpSession.setAttribute("username",userFromBase.getUsername());
        }
        else{
            responseEntity =  ResponseEntity.customerError();
            responseEntity.putDataValue("msg","账号密码错误");
        }
        httpSession.setAttribute("username",userFromBase.getUsername());
        return responseEntity;
    }

    /**
     * web端注册用户
     * @param identityID
     * @param username
     * @param password
     * @param phone
     * @param power
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @PostMapping("/web/register")
    @ResponseBody
    public ResponseEntity register(@RequestParam String identityID,
                                   @RequestParam String username,
                                   @RequestParam String password,
                                   @RequestParam(required = false) String phone,
                                   @RequestParam int power,
                                   @RequestHeader String Authorization,
                                   HttpServletResponse response) throws IOException, TokenExpiredException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }

        if (power > 3 || power < 1){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }

        User userFromBase = userService.selectUserByIdentityId(identityID);
        if (userFromBase == null){
            responseEntity = ResponseEntity.ok();
            User user = new User();
            user.setIdentityID(identityID);
            user.setUsername(username);
            user.setPassword(password);
            user.setPower(power);
            user.setPhone(phone);
            user.setId(myUtil.getStringID());
            userService.insertWebUser(user);
            responseEntity.putDataValue("msg","注册成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","注册失败");
        }

        return responseEntity;
    }

    /**
     * 获取用户信息
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/web/getinfo")
    @ResponseBody
    public ResponseEntity preHandle(@RequestHeader String Authorization,
                                    HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        String token = Authorization;
        ResponseEntity responseData;
        //token不存在
        if (token != null) {
            responseData = ResponseEntity.ok();
            User user = JwtToken.unsign(token, User.class);
            //解密token后的userId与用户传来的userId不一致，大多是因为token过期
            if (user != null) {
                responseData.putDataValue("username",user.getUsername());
                responseData.putDataValue("power",user.getPower());
                responseData.putDataValue("nickName",user.getNickName());
                responseData.putDataValue("avatarUrl",user.getAvatar());
                responseData.putDataValue("phone",user.getPhone());
                return responseData;
            }
        }
        responseData = ResponseEntity.forbidden();
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
        return responseData;
    }

    /**
     * 微信小程序注册用户接口
     * @param model
     * @param code
     * @param rawData
     * @param signature
     * @param encrypteData
     * @param iv
     * @return
     */
    @ResponseBody
    @RequestMapping("/wx/register")
    public ResponseEntity doRegister(Model model,
                                      @RequestParam(value = "code",required = false) String code,
                                      @RequestParam(value = "rawData",required = false) String rawData,
                                      @RequestParam(value = "signature",required = false) String signature,
                                      @RequestParam(value = "encrypteData",required = false) String encrypteData,
                                      @RequestParam(value = "iv",required = false) String iv){

        ResponseEntity responseData;
        JSONObject rawDataJson = JSON.parseObject( rawData );
        JSONObject SessionKeyOpenId = myUtil.getSessionKeyOrOpenId( code );
        String openid = SessionKeyOpenId.getString("openid" );
        String sessionKey = SessionKeyOpenId.getString( "session_key" );

        //通过openid来查询此用户是否存在
        User user = userService.selectUserByOpenid( openid );
        System.out.println("当前user为：" + user);
        //生成id
        String uid = myUtil.getStringID();
        if(user==null){
            responseData = ResponseEntity.ok();
            //入库
            int power = 3;
            String nickName = rawDataJson.getString( "nickName" );
            String avatar = rawDataJson.getString( "avatarUrl" );

            user = new User();
            user.setPower(power);
            user.setId( uid );
            user.setSessionKey( sessionKey );
            user.setOpenid( openid );
            user.setAvatar( avatar );
            user.setNickName( nickName );
            userService.insertWXUser( user );
            responseData.putDataValue("msg","注册成功");
            responseData.putDataValue("timestamp",myUtil.getTime());
            System.out.println("插入数据库成功");
        }else {
            //已存在
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","用户已存在");
            responseData.putDataValue("timestamp",myUtil.getTime());
            System.out.println("用户openid已存在,不需要插入");
        }
        return responseData;
    }

    /**
     * 微信小程序登陆接口
     * @param model
     * @param code
     * @param rawData
     * @param signature
     * @param encrypteData
     * @param iv
     * @return
     * @throws UnsupportedEncodingException
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/wx/login")
    public ResponseEntity doLogin(Model model,
                                     @RequestParam(value = "code",required = false) String code,
                                     @RequestParam(value = "rawData",required = false) String rawData,
                                     @RequestParam(value = "signature",required = false) String signature,
                                     @RequestParam(value = "encrypteData",required = false) String encrypteData,
                                     @RequestParam(value = "iv",required = false) String iv) throws UnsupportedEncodingException, JsonProcessingException {
        ResponseEntity responseEntity;
        JSONObject SessionKeyOpenId = myUtil.getSessionKeyOrOpenId( code );
        String openid = SessionKeyOpenId.getString("openid" );
        //通过openid来查询此用户是否存在
        User user = userService.selectUserByOpenid( openid );
        if(user == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "用户不存在");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
        }else {
            responseEntity = ResponseEntity.ok();
            //给用户jwt加密生成token
            String token = JwtToken.sign(user, 30L * 60L * 1000L);
            //封装成对象返回给客户端
            responseEntity.putDataValue("openid", user.getOpenid());
            responseEntity.putDataValue("token", token);
            responseEntity.putDataValue("timestamp",myUtil.getTime());
        }
        return responseEntity;
    }

    /**
     * 微信获取用户信息接口
     * @param Authorization
     * @param response
     * @return responseData
     * @throws Exception
     */
    @PostMapping("/wx/getinfo")
    @ResponseBody
    public ResponseEntity getWxInfo(@RequestHeader String Authorization,
                                    HttpServletResponse response) throws IOException {
        ResponseEntity responseData;
        String token = Authorization;
        //token不存在
        if (token != null) {
            responseData = ResponseEntity.ok();
            User user = JwtToken.unsign(token, User.class);
            //解密token后的userId与用户传来的userId不一致，大多是因为token过期
            if (user != null) {
                responseData.putDataValue("username",user.getUsername());
                responseData.putDataValue("power",user.getPower());
                responseData.putDataValue("nickName",user.getNickName());
                responseData.putDataValue("avatarUrl",user.getAvatar());
                return responseData;
            }
        }
        responseData = ResponseEntity.forbidden();
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
        return responseData;
    }

    /**
     * 根据id修改用户信息接口
     * @param password
     * @param avatar
     * @param phone
     * @param nickName
     * @param identityID
     * @param username
     * @param id
     * @param Authorization
     * @param response
     * @return
     */
    @PostMapping("/web/update_info_id")
    @ResponseBody
    public ResponseEntity updateUserInfoById(@RequestParam(required = false) String password,
                                             @RequestParam(required = false) String avatar,
                                             @RequestParam(required = false) String phone,
                                             @RequestParam(required = false) String nickName,
                                             @RequestParam(required = false) String identityID,
                                             @RequestParam(required = false) String username,
                                             @RequestParam(required = false) String id,
                                             @RequestHeader String Authorization,
                                             HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }

        //通过查询id来判断此用户是否存在
        User user = userService.selectUserById(id);
        if (user == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else {
            responseData = ResponseEntity.ok();
            user.setPassword(password);
            user.setAvatar(avatar);
            user.setPhone(phone);
            user.setNickName(nickName);
            user.setIdentityID(identityID);
            user.setUsername(username);
            //修改信息
            userService.updateUserInfoByID(user);
            responseData.putDataValue("identityId",user.getIdentityID());
            responseData.putDataValue("username",user.getUsername());
            responseData.putDataValue("id",user.getId());
            responseData.putDataValue("nickName",user.getNickName());
            responseData.putDataValue("phone",user.getPhone());
            responseData.putDataValue("power",user.getPower());
            responseData.putDataValue("avatar",user.getAvatar());
            System.out.println("修改数据成功");
        }
        return responseData;
    }

    /**
     * 修改自己信息接口
     * @param password
     * @param avatar
     * @param phone
     * @param nickName
     * @param identityID
     * @param username
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/web/update_info")
    @ResponseBody
    public ResponseEntity updateUserInfoByMyself(@RequestParam(required = false) String password,
                                             @RequestParam(required = false) String avatar,
                                             @RequestParam(required = false) String phone,
                                             @RequestParam(required = false) String nickName,
                                             @RequestParam(required = false) String identityID,
                                             @RequestParam(required = false) String username,
                                                 @RequestHeader String Authorization,
                                             HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        if (user == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else {
            responseData = ResponseEntity.ok();
            user.setPassword(password);
            user.setAvatar(avatar);
            user.setPhone(phone);
            user.setNickName(nickName);
            user.setIdentityID(identityID);
            user.setUsername(username);
            //修改信息
            userService.updateInfoByMyself(user);
            responseData.putDataValue("identityId",user.getIdentityID());
            responseData.putDataValue("username",user.getUsername());
            responseData.putDataValue("id",user.getId());
            responseData.putDataValue("nickName",user.getNickName());
            responseData.putDataValue("phone",user.getPhone());
            responseData.putDataValue("power",user.getPower());
            responseData.putDataValue("avatar",user.getAvatar());
            System.out.println("修改数据成功");
        }
        return responseData;
    }

    /**
     * 修改权限接口
     * @param id
     * @param power
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/web/update_power")
    @ResponseBody
    public ResponseEntity updateUserPower(@RequestParam(required = false) String id,
                                          @RequestParam(required = false) int power,
                                          @RequestHeader String Authorization,
                                                 HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        //通过查询id来判断此用户是否存在
        User user = userService.selectUserById(id);
        if (user == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","没有该用户");
        }else{
            //不能修改超级管理员权限
            if (user.getPower() == 1){
                responseData = ResponseEntity.badRequest();
                responseData.putDataValue("msg","不能修改超级管权限");
            }else {
                responseData = ResponseEntity.ok();
                user.setPower(power);
                //修改权限
                responseData.putDataValue("userId",user.getId());
                responseData.putDataValue("power",user.getPower());
                System.out.println("修改数据成功");
            }
        }
        return responseData;
    }

    /**
     * 用户列表接口
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param response
     * @param Authorization
     * @return
     * @throws IOException
     */
    @PostMapping("/web/user_list")
    @ResponseBody
    public ResponseEntity selectUser(@RequestParam(value = "size",required = false,defaultValue = "10") int size,
                                     @RequestParam(value = "page",required = false,defaultValue = "1") int page,
                                     @RequestParam(value = "sort",required = false) String sort,
                                     @RequestParam(value = "asc",required = false) String asc,
                                     @RequestHeader String Authorization,
                                     HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        PageBean<User> pagemsg = userService.selectUserByPage(size, page, sort, asc);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("records",pagemsg);
        return responseData;
    }



    /**
     * 获取微信小程序登陆的手机号
     * 但需要企业认证，所以就放弃了
     * @param model
     * @param code
     * @param rawData
     * @param signature
     * @param encrypteData
     * @param iv
     * @return
     */
    @ResponseBody
    @RequestMapping("/wx/phone")
    public String getPhone(Model model,
                                     @RequestParam(value = "code",required = false) String code,
                                     @RequestParam(value = "rawData",required = false) String rawData,
                                     @RequestParam(value = "signature",required = false) String signature,
                                     @RequestParam(value = "encrypteData",required = false) String encrypteData,
                                     @RequestParam(value = "iv",required = false) String iv){
        ResponseEntity responseData;
        JSONObject SessionKeyOpenId = myUtil.getSessionKeyOrOpenId( code );
        String sessionKey = SessionKeyOpenId.getString( "session_key" );

        String phone = myUtil.getPhone(sessionKey,encrypteData,iv);
        System.out.println(phone);
        return phone;
    }

}
